package com.qu.waibao.nearby;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.navi.BaiduMapAppNotSupportNaviException;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.google.gson.reflect.TypeToken;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;
import com.qu.waibao.AppConfig;
import com.qu.waibao.MyApplication;
import com.qu.waibao.R;
import com.qu.waibao.baidu.DingweiAdapter;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.base.BaseFragment;
import com.qu.waibao.base.BaseRecyclerAdapter;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.BaiduUtil;
import com.qu.waibao.utils.GsonUtil;
import com.qu.waibao.utils.TDevice;
import com.qu.waibao.utils.ToastUtil;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
     * Created by quguangle on 2018/7/21.
 */

public class NearbyFragment extends BaseFragment implements
        OnGetGeoCoderResultListener,View.OnClickListener,
        DingweiAdapter.OnItemDangClickListener{
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.et_search)
    EditText et_search;
    @BindView(R.id.mMapView)
    TextureMapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private GeoCoder mGeoSearch; //地理编码
    private DingweiAdapter adapter;
    private String longitude = "";
    private String latitude = "";
    private String keywords = "";
    private double curLatitude;
    private double curLongitude;
    private String address = "";
    private LatLng latLng;
    private boolean isFirstLoc = true;
    // 初始化全局 bitmap 信息，不用时及时 recycle
    BitmapDescriptor bdA = BitmapDescriptorFactory
            .fromResource(R.drawable.lan);
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_nearby;
    }
    @Override
    protected void initWidget(View root) {
        super.initWidget(root);
        ll_back.setVisibility(View.GONE);
        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode==KeyEvent.KEYCODE_SEARCH && event.getAction()==KeyEvent.ACTION_UP){
                    keywords = et_search.getText().toString().trim()+"";
                    requestData();
                    return true;
                }
                return false;
            }
        });
        initMap();
        if(LocationUtils.Mylocation != null){
            latitude = String.valueOf(LocationUtils.Mylocation.getLatitude());
            longitude = String.valueOf(LocationUtils.Mylocation.getLongitude());
            curLongitude = LocationUtils.Mylocation.getLongitude();
            curLatitude = LocationUtils.Mylocation.getLatitude();
        }
    }
    //配置定位SDK参数
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation
        // .getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);
        option.setOpenGps(true); // 打开gps

        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    private void initMap() {
        //初始化地理编码

        // 初始化搜索模块，注册事件监听
        mGeoSearch = GeoCoder.newInstance();
        mGeoSearch.setOnGetGeoCodeResultListener(this);

        //获取地图控件引用
        mBaiduMap = mMapView.getMap();
        //普通地图
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mBaiduMap.setMyLocationEnabled(true);

        //默认显示普通地图
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mLocationClient = new LocationClient(MyApplication.getInstance());     //声明LocationClient类
        //配置定位SDK参数
        initLocation();
        mLocationClient.registerLocationListener(new MyLocationListener());    //注册监听函数
        //开启定位
        mLocationClient.start();
        //图片点击事件，回到定位点
        //mLocationClient.requestLocation();

        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                MapStatusUpdate center = MapStatusUpdateFactory.newLatLng(latLng);
                mBaiduMap.animateMapStatus(center);
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                startReverseGeoCode(mapStatus.target);
            }
        });
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                LatLng latLng = marker.getPosition();
                String lat = String.valueOf(latLng.latitude);
                String Lng = String.valueOf(latLng.longitude);
                for(int i = 0;i< adapter.getItems().size();i++){
                    ShopPerson shopPerson = adapter.getItems().get(i);
                    if(lat.equals(shopPerson.getLatitude()) && Lng.equals(shopPerson.getLongitude())){
                        shopPerson.setFlag(1);
                    }else {
                        shopPerson.setFlag(0);
                    }
                }
                adapter.notifyItemRangeChanged(0,adapter.getItems().size());
                return false;
            }
        });

    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new DingweiAdapter(getActivity(), BaseRecyclerAdapter.NEITHER);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, long itemId) {
                ShopPerson item = adapter.getItems().get(position);
                Intent intent = new Intent(getActivity(),ShopindroceActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("ShopPerson",item);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        adapter.setOnItemDangClickListener(this);
        requestData();
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onDestroy() {
        mMapView.onDestroy();
        mGeoSearch.destroy();
        super.onDestroy();
        if(bdA != null){
            bdA.recycle();
            bdA = null;
        }
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        TDevice.closeKeyboard(et_search);
        latLng = reverseGeoCodeResult.getLocation();
        longitude = String.valueOf(reverseGeoCodeResult.getLocation().longitude);
        latitude = String.valueOf(reverseGeoCodeResult.getLocation().latitude);
        requestData();
    }

    //根据经纬度来查找
    public void startReverseGeoCode(LatLng ptCenter){
        // 反Geo搜索
        mGeoSearch.reverseGeoCode(new ReverseGeoCodeOption()
                .location(ptCenter));
    }

    @OnClick(R.id.tv_search)
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_search:
                keywords = et_search.getText().toString().trim()+"";
                requestData();
                break;
        }
    }

    @Override
    public void onItemDangClick(int position) {
         address = adapter.getItems().get(position).getAddress_full();
         final double lat = Double.valueOf(adapter.getItems().get(position).getLatitude());
         final double lng = Double.valueOf(adapter.getItems().get(position).getLongitude());
        NiceDialog.init()
                .setLayoutId(R.layout.daohang_layout)     //设置dialog布局文件
                .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                    int flag = 0;
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        final TextView tv_gaode = holder.getView(R.id.tv_gaode);
                        final TextView tv_baidu = holder.getView(R.id.tv_baidu);
                        holder.setOnClickListener(R.id.tv_gaode, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tv_gaode.setTextColor(Color.parseColor("#f29f1b"));
                                tv_baidu.setTextColor(Color.parseColor("#333333"));
                                flag = 1;
                            }
                        });
                        holder.setOnClickListener(R.id.tv_baidu, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tv_gaode.setTextColor(Color.parseColor("#333333"));
                                tv_baidu.setTextColor(Color.parseColor("#f29f1b"));
                                flag = 2;
                            }
                        });
                        holder.setOnClickListener(R.id.tv_cancel, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        holder.setOnClickListener(R.id.tv_sure, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                if(flag == 1){
                                    gaodeNav(curLatitude,curLongitude,address);
                                }else if(flag == 2){
                                    startNavi(curLatitude,curLongitude,lat,lng);
                                }
                            }
                        });
                    }
                })
                .setMargin(30)
                .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                .setShowBottom(false)     //是否在底部显示dialog，默认flase
                .setOutCancel(true)     //点击dialog外是否可取消，默认true
                .show(getChildFragmentManager());     //显示dialog
    }


    public void requestData(){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.shop_list_get);
        map.put("userid", AppConfig.getString("userid"));
        map.put("keyword",keywords);
        map.put("longitude",longitude);
        map.put("latitude",latitude);
        NetManager.getInstance().request(getActivity(), map, false, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                List<ShopPerson> list = GsonUtil.createGson().fromJson(result,
                        new TypeToken<List<ShopPerson>>(){}.getType());
                adapter.clear();
                adapter.addAll(list);
                mBaiduMap.clear();
                for(int i = 0;i<list.size();i++){
                    Double latitude = Double.valueOf(list.get(i).getLatitude());
                    Double longitude = Double.valueOf(list.get(i).getLongitude());
                    mBaiduMap.addOverlay(new MarkerOptions()
                            .position(new LatLng(latitude,longitude))
                            .icon(bdA)
                            .zIndex(9));
                }
            /*    // 设置有效区域
                LatLngBounds bounds = new LatLngBounds.Builder()
                        .include(latLng).build();
                MapStatusUpdate u = MapStatusUpdateFactory
                        .newLatLngBounds(bounds,mMapView.getWidth(),mMapView.getHeight());
                mBaiduMap.setMapStatus(u);*/
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //开启百度导航
    public void startNavi(double LATITUDE_QIDIAN,double LONGTITUDE_QIDIAN,double endLag,double endLng) {
        LatLng ll_location = new LatLng(LATITUDE_QIDIAN,LONGTITUDE_QIDIAN);
        LatLng ll = new LatLng(endLag,endLng);
        NaviParaOption para = new NaviParaOption();
        para.startPoint(ll_location);
        para.startName("从这里开始");
        para.endPoint(ll);
        para.endName("到这里结束");
        try {
            BaiduMapNavigation.openBaiduMapNavi(para, getContext());
        } catch (BaiduMapAppNotSupportNaviException e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "您尚未安装百度地图客户端", Toast.LENGTH_LONG).show();
        }
    }


    public void gaodeNav(double LATITUDE_B,double LONGTITUDE_B,String end){
        Intent intent;
        if(BaiduUtil.isAvilible(MyApplication.getInstance(),"com.autonavi.minimap")){ //传入指定应用包名
            try {
                intent = Intent.getIntent("androidamap://route?sourceApplication=softname&sname=我的位置&dlat="+LATITUDE_B+"&dlon="+LONGTITUDE_B+"&dname="+end+"&dev=0&m=0&t=1");
                startActivity(intent); //启动调用
            } catch (Exception e) {
            }
        }else{
            Toast.makeText(getActivity(), "您尚未安装高德地图客户端", Toast.LENGTH_LONG).show();
        }
    }

    //实现BDLocationListener接口,BDLocationListener为结果监听接口，异步获取定位结果
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            latLng = new LatLng(location.getLatitude(), location.getLongitude());
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);
            // 当不需要定位图层时关闭定位图层
            //mBaiduMap.setMyLocationEnabled(false);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(15.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
            if(location.getLocType() == BDLocation.TypeCriteriaException){
                 ToastUtil.show(mContext,"定位失败");
            }
        }
    }

}
